import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import pool from '../config/db.js';

const router = express.Router();

// 获取用户的所有地址
router.get('/', authenticateToken, async (req, res) => {
  try {
    const [addresses] = await pool.query(
      'SELECT * FROM addresses WHERE user_id = ? ORDER BY created_at DESC',
      [req.user.id]
    );
    
    res.json(addresses);
  } catch (error) {
    console.error('Error fetching addresses:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取地址失败' 
    });
  }
});

// 添加新地址
router.post('/', authenticateToken, async (req, res) => {
  try {
    // 支持两种字段名称：name 或 recipient
    const { name, recipient, phone, province, city, address, postcode, is_default } = req.body;
    
    // 使用 recipient 字段如果 name 不存在
    const recipientName = name || recipient;
    
    // 验证必填字段
    if (!recipientName || !phone || !province || !city || !address) {
      return res.status(400).json({
        success: false,
        message: '请填写所有必填字段'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 如果设置为默认地址，先将其他地址设为非默认
      if (is_default) {
        await connection.query(
          'UPDATE addresses SET is_default = 0 WHERE user_id = ?',
          [req.user.id]
        );
      }
      
      // 插入新地址
      const [result] = await connection.query(
        'INSERT INTO addresses (user_id, name, phone, province, city, address, postcode, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
        [req.user.id, recipientName, phone, province, city, address, postcode, is_default ? 1 : 0]
      );
      
      // 获取新插入的地址
      const [newAddress] = await connection.query(
        'SELECT * FROM addresses WHERE id = ?',
        [result.insertId]
      );
      
      await connection.commit();
      
      res.status(201).json({
        success: true,
        message: '地址添加成功',
        address: newAddress[0]
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('Error adding address:', error);
    res.status(500).json({
      success: false,
      message: '添加地址失败'
    });
  }
});

// 更新地址
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const addressId = req.params.id;
    // 支持两种字段名称：name 或 recipient
    const { name, recipient, phone, province, city, address, postcode, is_default } = req.body;
    
    // 使用 recipient 字段如果 name 不存在
    const recipientName = name || recipient;
    
    // 验证必填字段
    if (!recipientName || !phone || !province || !city || !address) {
      return res.status(400).json({
        success: false,
        message: '请填写所有必填字段'
      });
    }
    
    // 检查地址是否属于当前用户
    const [addressCheck] = await pool.query(
      'SELECT id FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, req.user.id]
    );
    
    if (addressCheck.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在或无权限修改'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 如果设置为默认地址，先将其他地址设为非默认
      if (is_default) {
        await connection.query(
          'UPDATE addresses SET is_default = 0 WHERE user_id = ?',
          [req.user.id]
        );
      }
      
      // 更新地址
      await connection.query(
        'UPDATE addresses SET name = ?, phone = ?, province = ?, city = ?, address = ?, postcode = ?, is_default = ? WHERE id = ?',
        [recipientName, phone, province, city, address, postcode, is_default ? 1 : 0, addressId]
      );
      
      await connection.commit();
      
      res.json({
        success: true,
        message: '地址更新成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('Error updating address:', error);
    res.status(500).json({
      success: false,
      message: '更新地址失败'
    });
  }
});

// 删除地址
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const addressId = req.params.id;
    
    // 检查地址是否属于当前用户
    const [addressCheck] = await pool.query(
      'SELECT id, is_default FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, req.user.id]
    );
    
    if (addressCheck.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在或无权限删除'
      });
    }
    
    // 删除地址
    await pool.query('DELETE FROM addresses WHERE id = ?', [addressId]);
    
    // 如果删除的是默认地址，将最新的地址设为默认
    if (addressCheck[0].is_default) {
      const [addresses] = await pool.query(
        'SELECT id FROM addresses WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
        [req.user.id]
      );
      
      if (addresses.length > 0) {
        await pool.query(
          'UPDATE addresses SET is_default = 1 WHERE id = ?',
          [addresses[0].id]
        );
      }
    }
    
    res.json({
      success: true,
      message: '地址删除成功'
    });
  } catch (error) {
    console.error('Error deleting address:', error);
    res.status(500).json({
      success: false,
      message: '删除地址失败'
    });
  }
});

// 设置默认地址
router.put('/:id/default', authenticateToken, async (req, res) => {
  try {
    const addressId = req.params.id;
    
    // 检查地址是否属于当前用户
    const [addressCheck] = await pool.query(
      'SELECT id FROM addresses WHERE id = ? AND user_id = ?',
      [addressId, req.user.id]
    );
    
    if (addressCheck.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在或无权限修改'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 将所有地址设为非默认
      await connection.query(
        'UPDATE addresses SET is_default = 0 WHERE user_id = ?',
        [req.user.id]
      );
      
      // 将指定地址设为默认
      await connection.query(
        'UPDATE addresses SET is_default = 1 WHERE id = ?',
        [addressId]
      );
      
      await connection.commit();
      
      res.json({
        success: true,
        message: '默认地址设置成功'
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('Error setting default address:', error);
    res.status(500).json({
      success: false,
      message: '设置默认地址失败'
    });
  }
});

export default router; 